// src/utils/mqttRequest.js
import store from '@/store'
import config from '@/config'
import { getToken } from '@/utils/auth'
import { showErrorToast, showConfirm } from '@/utils/common'
import mqttClient from '@/utils/mqttClient'

// 初始化MQTT客户端
mqttClient.init();

// 监听服务器就绪事件
let serverReadyResolve;
const serverReady = new Promise((resolve) => {
  serverReadyResolve = resolve;
});

mqttClient.on('serverReady', () => {
  console.log('[MQTT] 服务器已就绪');
  serverReadyResolve();
});

mqttClient.on('unauthorized', (message) => {
  console.log('检测到未授权状态');
  showConfirm('登录状态已过期，请重新登录').then(res => {
    if (res.confirm) {
      store.dispatch('LogOut').then(() => {
        uni.reLaunch({ url: '/pages/login' });
      });
    }
  });
});

mqttClient.on('apiError', ({ code, message }) => {
  showErrorToast(`请求错误 (${code}): ${message}`);
});

// MQTT请求方法
export const mqttRequest = async (request) => {
  // 等待服务器就绪
  if (!mqttClient.serverClientId) {
    console.log('[MQTT] 等待服务器客户端ID...');
    await serverReady;
  }
  
  // 添加认证头
  const headers = request.headers || {};
  if (getToken() && (headers.isToken === undefined || headers.isToken)) {
    headers['Authorization'] = 'Bearer ' + getToken();
  }
  headers[config.apISafe.AppKeyName]=config.apISafe.AppKey;
  headers[config.apISafe.TimeStampName]=Math.floor(Date.now() / 1000);
  
  console.log("headers",headers)
  // 构建请求数据
  const requestData = {
    url: `${request.url}`,
    method: request.method || 'get',
    headers: headers,
    data: request.data
  };
  
  try {
    // 根据方法类型发送请求
    let response;
    switch ((request.method || 'get').toLowerCase()) {
      case 'get':
        response = await mqttClient.get(request.url, request.data, headers);
        break;
      case 'post':
        response = await mqttClient.post(request.url, request.data, headers);
        break;
      case 'put':
        response = await mqttClient.put(request.url, request.data, headers);
        break;
      case 'delete':
        response = await mqttClient.delete(request.url, request.data, headers);
        break;
      default:
        throw new Error(`不支持的HTTP方法: ${request.method}`);
    }
    
    // 修复：确保返回完整响应
    console.log('[MQTT请求] 请求成功:', response);
    return response;
  } catch (error) {
    console.error('[MQTT请求] 错误:', error);
    showErrorToast(error.message || '请求失败');
    throw error;
  }
};